/**
 * 构建基于 koa2 的 http server，模拟 http 请求数据
 * 与 fetch.mock 的区别是：fetch.mock 拦截了 fetch 函数，没有真实的发起网络请求
 * 而用 http server 模拟的数据则是模拟了一个服务，请求时发起了真正的网络请求
 */
import Koa from 'koa'
const koaBody = require('koa-body');
import {sleep} from '../src/base/base'

const app = new Koa();

app.use(koaBody({
      multipart:true, // 支持文件上传
      // encoding:'gzip',
      formidable:{
          // uploadDir:path.join(__dirname,'public/upload/'), // 设置文件上传目录
          keepExtensions: true,    // 保持文件的后缀
          maxFieldsSize:8 * 1024 * 1024, // 文件上传大小
          onFileBegin:(name,file) => { // 文件上传前的设置
              // console.log(`name: ${name}`);
              // console.log(file);
          },
      },
      onError:function(parsingError){
          console.log('==== error ====')
          console.log(parsingError)
      }
  })
);

const router = require('koa-router')();

var routers = require('./mock/')

//遍历对象，对对象中的地址进行数据拦截
if(routers){

    for(var key in routers){
        var fun = routers[key];
        if(fun && typeof fun == 'function'){
            router.all(key, (function(key,fun){
                //采用闭包，保存变量
                return async (ctx, next) =>{
                    await fun(ctx, next);
                }
            })(key,fun));
        }
    }
}

//添加路由
app.use(router.routes());

var webpack = require('webpack');

const webpackConfig = require('./webpack.config')

const koaWebpack = require('koa-webpack');

var compileComplete = false;
async function configWebpack() {

    const middleware = await koaWebpack({

        config: webpackConfig,
        hotClient: undefined,
        devMiddleware:{
            watchOptions: {
                aggregateTimeout: 300,
                poll: true
            },
            reload: true,
            publicPath: webpackConfig.output.publicPath,
            stats: {
                colors: true
            },
            serverSideRender: true,
        }
    })

    middleware.devMiddleware.waitUntilValid(() => {
        compileComplete = true;
    });
    app.use(middleware)
}


module.exports = async () => {

    if(process.env.KOA != 'true'){
        //如果不启动 KOA 立即返回
        return new Promise(resolve => resolve());
    }
    global.__KOA2_APP__ = app;

    await configWebpack();

    return new Promise(resolve => {
        app.listen(3001, async ()=>{

            while (!compileComplete) {
                await sleep(5 * 100)
            }
            resolve();
        });
    })
};
